﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MusicStore.WebMVC.Models
{
    public class ShoppingCart
    {
        readonly MusicStoreEntities db = new MusicStoreEntities();

        public string ShoppingCartId { get; set; }

        public const string CartSessionKey = "CartId";

        //static method allow out controller obtain a cart object
        // We're using HttpContextBase to allow access to cookies. 

        static public ShoppingCart GetCart(HttpContextBase context)
        {
            ShoppingCart cart = new ShoppingCart();

            if (context.Session[CartSessionKey] == null)
            {
                if (string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    // Generate a new random GUID using System.Guid class  
                    context.Session[CartSessionKey] = Guid.NewGuid().ToString();
                }
                else
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
            }

            cart.ShoppingCartId = context.Session[CartSessionKey].ToString();

            return cart;
        }

        // Helper method to simplify shopping cart calls 

        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }

        //AddToCart

        public void AddToCart(Album album)
        {
            //check for album has already 
            //(cartId & albumId, if not create new and add, else >> increment)

            var cartItem = db.Carts.SingleOrDefault(
                                c => c.CartId == ShoppingCartId &&
                                    c.AlbumId == album.AlbumId);

            if (cartItem == null)
            {
                cartItem = new Cart
                {
                    CartId = ShoppingCartId,
                    AlbumId = album.AlbumId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };

                db.Carts.Add(cartItem);
            }
            else
            {
                cartItem.Count++;
            }

            db.SaveChanges();
        }

        //RemoveFromCart

        public int RemoveFromCart(int id)
        {
            //get cart details
            var cartItem = db.Carts.SingleOrDefault(
                                c => c.CartId == ShoppingCartId &&
                                    c.RecordId == id);

            //remove when count = 1 , else decrement 
            int count = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    count = cartItem.Count;
                }
                else
                    db.Carts.Remove(cartItem);

                db.SaveChanges();
            }

            return count;
        }

        //EmptyCart

        public void EmptyCart()
        {
            var cartItems = db.Carts.Where(c => c.CartId == ShoppingCartId);

            foreach (var item in cartItems)
                db.Carts.Remove(item);

            db.SaveChanges();
        }

        //GetCartItems: retrieves list of item in cart

        public List<Cart> GetCartItems()
        {
            return db.Carts.Where(c => c.CartId == ShoppingCartId).ToList();
        }

        //GetCount: retrieves total number of items in cart

        public int GetCount()
        {
            return db.Carts.Where(c => c.CartId == ShoppingCartId)
                            .Sum(c => (int?)c.Count) ?? 0;

        }

        //GetTotal: retrieve total cost of all items in cart

        public decimal GetTotal()
        {
            return db.Carts.Where(c => c.CartId == ShoppingCartId)
                            .Sum(c => (decimal?)(c.Album.Price * c.Count)) ?? 0;
        }

        //CreateOrder: convert shopping cart to an order during the checkout phase

        public int CreateOrder(Order order)
        {
            var cartItems = GetCartItems();

            //order total of the shopping cart
            decimal orderTotal = 0;

            //interate over the items in the shopping cart, create order detail for each
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    OrderId = order.OrderId,
                    AlbumId = item.AlbumId,
                    UnitPrice = item.Album.Price,
                    Quantity = item.Count
                };

                db.OrderDetails.Add(orderDetail);

                orderTotal += item.Album.Price * item.Count;
            }

            //order total
            order.Total = orderTotal;

            //save change
            db.SaveChanges();
           
            //return id for confirmation number
            return order.OrderId;
        }

        //MigrateCart: when user logged in, migrate their shopping cart to
        //be associated with their username

        public void MigrateCart(string userName)
        {
            var shoppingCart = db.Carts.Where(c => c.CartId == ShoppingCartId);

            foreach (var item in shoppingCart)
            {
                item.CartId = userName;
            }

            db.SaveChanges();
        }
    }
}